package com.dapeis.api.controller.collocation.impl;

import java.security.InvalidParameterException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.core.exception.InvalidParamException;
import com.ag.core.exception.SysTipsException;
import com.ag.module.common.api.service.city.CityService;
import com.ag.utils.DateUtils;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.api.controller.RestController;
import com.dapeis.api.controller.collocation.IInformationCotroller;
import com.dapeis.core.utils.StringUtil;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Collocation;
import com.dapeis.domain.CollocationInformation;
import com.dapeis.domain.StylistCity;
import com.dapeis.domain.ext.CollocationExt;
import com.dapeis.service.COSFileService;
import com.dapeis.service.CollocationInformationService;
import com.dapeis.service.CollocationService;
import com.dapeis.service.StylistCityService;
import com.dapeis.service.TIMService;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

@Controller
@RequestMapping("/dps/information")
public class InformationCotrollerImpl extends RestController implements
	IInformationCotroller {

    @Resource
    CollocationInformationService inforService;

    @Resource
    COSFileService cosFileService;

    @Resource
    CollocationService collocationService;

    @Resource
    TIMService timService;
    @Resource
    StylistCityService stylistCityService;

    /**
     * 搭配师提交资料
     * 
     * @param workTime
     *            工作性质:全职、兼职
     * @param sex
     * @param name
     * @param IDcardNo
     * @param serverCity
     * @param qualification
     * @param birthday
     * @param IDcardFront
     *            身份证正面照片
     * @param IDcarContray
     *            身份证反面
     */

    @Override
    public JsonElement save(Integer workTime, String name, Integer sex,
	    String birthday, String IDcardNo, MultipartFile IDcardFront,
	    MultipartFile IDcardContrary, String serverCity,
	    String qualification, HttpServletRequest request) {
	// 未提交和审核未通过才能提交审核
	Integer auditStatus = getThreadLocalCollocation().getAuditState();
	if (auditStatus == StylistConstants.Audit.WAIT_AUDIT
		|| auditStatus == StylistConstants.Audit.PASS_AUDIT) {
	    throw new SysTipsException("请勿重复提交审核资料!");
	}
	// 检查参数
	checkParameter(workTime, sex, name, IDcardNo, serverCity,
		qualification, birthday, IDcardFront, IDcardContrary);
	// 存在就更新,Controller中控制,只有拒审才进来
	CollocationInformation dbInformation = inforService
		.getCollocaitonInformationByCollocationId(getThreadLocalCollocationId());

	CollocationInformation information = initData(dbInformation, workTime,
		name, sex, birthday, IDcardNo,
		doUploadImg(IDcardFront, request),
		doUploadImg(IDcardContrary, request), serverCity, qualification);
	if (null == dbInformation) {
	    inforService.insertSelective(information);
	}else{
	    inforService.updateByPrimaryKeySelective(information);
	}

	Collocation collocaiton = getThreadLocalCollocation();
	collocaiton.setAuditState(StylistConstants.Audit.WAIT_AUDIT);
	collocaiton.setInforId(information.getId());
	collocationService.updateByPrimaryKeySelective(collocaiton);
	JsonObject json = buildSuccess();
	return json;
    }

    /**
     * 初始化参数
     * 
     * @param workTime
     * @param name
     * @param sex
     * @param birthday
     * @param IDcardNo
     * @param IDcardFrontImg
     *            反面照片
     * @param IDcardContraryImg
     *            正面照片
     * @param serverCity
     * @param qualification
     * @return
     */
    private CollocationInformation initData(
	    CollocationInformation _information, Integer workTime, String name,
	    Integer sex, String birthday, String IDcardNo,
	    String IDcardFrontImg, String IDcardContraryImg, String serverCity,
	    String qualification) {
	CollocationInformation information = _information;
	if (null == information) {
	    information = new CollocationInformation();
	    information.setCollocationId(getThreadLocalCollocationId());
	    information
		    .setCreateTime(Calendar.getInstance().getTimeInMillis() / 1000);
	}
	information.setWorkTime(workTime);
	information.setRealName(name);
	information.setSex(sex);
	try {
	    // 生日格式:2016-09-12
	    SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD);
	    information.setBirthday(sdf.parse(birthday).getTime() / 1000);
	} catch (ParseException e) {
	    throw new InvalidParameterException("生日数据非法!");
	}
	information.setIDcardContrary(IDcardContraryImg);
	information.setIDcardFront(IDcardFrontImg);
	information.setIDcardNo(IDcardNo);
	information.setServerCity(serverCity);
	information.setQualification(qualification);
	return information;
    }

    /**
     * 上传图片
     * 
     * @param multipartFile
     * @param request
     * @return
     */
    private String doUploadImg(MultipartFile multipartFile,
	    HttpServletRequest request) {
	return cosFileService.saveFile(multipartFile,
		StylistConstants.UploadType.IDCARD, request);
    }

    /**
     * 检查参数
     * 
     * @param workTime
     * @param sex
     * @param name
     * @param iDcardNo
     * @param serverCity
     * @param qualification
     */

    private void checkParameter(Integer workTime, Integer sex, String name,
	    String iDcardNo, String serverCity, String qualification,
	    String birthday, MultipartFile IDcardFront,
	    MultipartFile IDcardContrary) {
	if (workTime != StylistConstants.WORKTIME.FULLTIME
		&& workTime != StylistConstants.WORKTIME.PARTTIME)
	    throw new InvalidParamException("工作时间不能为空!");
	if (StringUtil.isBlank(name))
	    throw new InvalidParameterException("姓名不能为空！");
	if (sex != StylistConstants.Sex.LADY && sex != StylistConstants.Sex.MAN)
	    throw new InvalidParamException("性别参数非法!");
	if (StringUtil.isBlank(serverCity)) {
	    throw new InvalidParamException("服务城市不能为空");
	} else {
	    StylistCity _city = stylistCityService.getCity(serverCity);
	    if (!(null != _city && _city.getLevelType().equals("3"))) {
		throw new InvalidParamException("服务城市非法!");
	    }
	}
	if (StringUtil.isBlank(qualification))
	    throw new InvalidParamException("个人资历不能为空!");
	if (StringUtil.isBlank(birthday))
	    throw new InvalidParamException("生日信息不能为空!");
	if (null == IDcardFront)
	    throw new InvalidParamException("请上传身份证正面照片!");
	if (null == IDcardContrary)
	    throw new InvalidParamException("请上传身份证反面照片!");
    }

    @Override
    public JsonElement updateCentre(MultipartFile headImg, String nickName,
	    String honor, String cityCode, String address, String goodStyle,
	    String remark, HttpServletRequest request) {
	Collocation collocation = collocationService
		.selectByPrimaryKey(getThreadLocalCollocationId());
	String img = cosFileService.saveFile(headImg,
		StylistConstants.UploadType.HEAD, request);
	Integer coId = getThreadLocalCollocationId();
	collocation.setId(coId);
	collocation.setAddress(address);
	collocation.setHonor(honor);
	collocation.setGoodStyle(goodStyle);
	collocation.setNickName(nickName);
	collocation.setCityCode(cityCode);
	collocation.setRemark(remark);
	collocation.setHeadImg(img);
	Example example = new Example(Collocation.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Collocation.PROPERTY_STATE,
		StylistConstants.State.NORMAL);
	criteria.andEqualTo(Collocation.PROPERTY_ID, coId);
	collocationService.updateByExampleSelective(collocation, example);

	boolean result = timService.updateAccout(collocation);
	logger.info("register QTIM CollocationId +" + collocation.getId()
		+ ",Result:" + result);
	CollocationExt collocationExt = collocationService
		.getCollocationExtMapper().selectByPrimaryKey(
			getThreadLocalCollocationId());
	JsonObject json = buildSuccess();
	json.add("collocation", AGsonBuilder.create()
		.toJsonTree(collocationExt));
	return json;
    }

}
